#!/usr/bin/env python
#coding:utf-8

import socket
import re
import sys
import os

def findipfromdns(dnsserver,domain):
    host = ''
    for i in domain.split('.'):
        host += chr(len(i))+i
    index = os.urandom(2)
    data = '%s\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00%s\x00\x00\x01\x00\x01'%(index, host)
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(15)
    s.sendto(data, (dnsserver,53))
    respenon = s.recv(512)
    iplist = []
    for i in re.findall("\xC0[\s\S]\x00\x01\x00\x01[\s\S]{6}([\s\S]{4})", respenon):
        ip =  '.'.join(str(ord(ii)) for ii in i)
        iplist.append(ip)
    iplist.sort()
    return iplist
if __name__ == '__main__':
    if len(sys.argv) == 1:
        print 'e.g. findipfromdns.py 223.5.5.5 baidu.com' 
    else:
        dnsserver = sys.argv[1]
        domain = sys.argv[2]
        print findipfromdns(dnsserver, domain)



